<?php

namespace App\Services;

use App\Constants\AbstractEnum;
use App\Constants\EmployeeStatusEnum;
use App\Constants\ContractTypeEnum;
use App\Constants\AttendanceStatusEnum;
use App\Constants\SalaryTypeEnum;
use App\Constants\InsuranceTypeEnum;
use App\Constants\FileTypeEnum;
use App\Constants\OperationTypeEnum;
use App\Constants\FileStatusEnum;
use App\Constants\StorageTypeEnum;
use App\Constants\FileCategoryEnum;
use App\Constants\UploadStatusEnum;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

/**
 * 常量管理服务
 * 统一管理所有系统常量，支持缓存和按需获取
 */
class ConstantsService
{
    /**
     * 缓存键前缀
     */
    private const CACHE_PREFIX = 'constants:';

    /**
     * 缓存过期时间（秒）
     */
    private const CACHE_TTL = 3600; // 1小时

    /**
     * 获取所有常量
     */
    public function getAllConstants(): array
    {
        return Cache::remember(self::CACHE_PREFIX . 'all', self::CACHE_TTL, function () {
            return [
                'employee_status' => EmployeeStatusEnum::toDetailArray(),
                'contract_type' => ContractTypeEnum::toDetailArray(),
                'attendance_status' => AttendanceStatusEnum::toDetailArray(),
                'salary_type' => SalaryTypeEnum::toDetailArray(),
                'insurance_type' => InsuranceTypeEnum::toDetailArray(),
                'file_type' => FileTypeEnum::toDetailArray(),
                'operation_type' => OperationTypeEnum::toDetailArray(),
                'file_status' => FileStatusEnum::toDetailArray(),
                'storage_type' => StorageTypeEnum::toDetailArray(),
                'file_category' => FileCategoryEnum::toDetailArray(),
                'upload_status' => UploadStatusEnum::toDetailArray(),
            ];
        });
    }

    /**
     * 获取指定模块的常量
     */
    public function getModuleConstants(string $module): array
    {
        $cacheKey = self::CACHE_PREFIX . $module;

        return Cache::remember($cacheKey, self::CACHE_TTL, function () use ($module) {
            return match ($module) {
                'employee_status' => EmployeeStatusEnum::toDetailArray(),
                'contract_type' => ContractTypeEnum::toDetailArray(),
                'attendance_status' => AttendanceStatusEnum::toDetailArray(),
                'salary_type' => SalaryTypeEnum::toDetailArray(),
                'insurance_type' => InsuranceTypeEnum::toDetailArray(),
                'file_type' => FileTypeEnum::toDetailArray(),
                'operation_type' => OperationTypeEnum::toDetailArray(),
                'file_status' => FileStatusEnum::toDetailArray(),
                'storage_type' => StorageTypeEnum::toDetailArray(),
                'file_category' => FileCategoryEnum::toDetailArray(),
                'upload_status' => UploadStatusEnum::toDetailArray(),
                default => []
            };
        });
    }

    /**
     * 获取指定常量值
     */
    public function getConstant(string $module, string|int $value): ?array
    {
        $constants = $this->getModuleConstants($module);
        
        foreach ($constants as $constant) {
            if ($constant['value'] === $value) {
                return $constant;
            }
        }
        
        return null;
    }

    /**
     * 验证常量值是否有效
     */
    public function isValidConstant(string $module, string|int $value): bool
    {
        return $this->getConstant($module, $value) !== null;
    }

    /**
     * 清除常量缓存
     */
    public function clearCache(string $module = null): void
    {
        if ($module) {
            Cache::forget(self::CACHE_PREFIX . $module);
        } else {
            Cache::forget(self::CACHE_PREFIX . 'all');
        }
        
        Log::info('Constants cache cleared', ['module' => $module]);
    }

    /**
     * 刷新常量缓存
     */
    public function refreshCache(): void
    {
        $this->clearCache();
        $this->getAllConstants(); // 重新生成缓存
        Log::info('Constants cache refreshed');
    }

    /**
     * 获取常量统计信息
     */
    public function getStatistics(): array
    {
        $allConstants = $this->getAllConstants();
        $stats = [];
        
        foreach ($allConstants as $module => $constants) {
            $stats[$module] = [
                'total' => count($constants),
                'enabled' => count(array_filter($constants, fn($c) => $c['enabled'] ?? true)),
                'last_updated' => now()->toISOString(),
            ];
        }
        
        return $stats;
    }
}
